#include "threadpool.h"
#include "../sql/sqlexec.h"
ThreadPool::ThreadPool(QObject *parent) : QObject(parent) {
  for (size_t i = 0; i < MAX_THREAD_NUM; i++) {
    _threads.push_back(new MyThread(parent));
    auto db = new SqlExec();
    db->moveToThread(_threads.back());
    db->open(QString("Q_con%1").arg(i));
    _threads.back()->setDB(db);
    _threads.back()->start();
  }
}

/**
 * @brief 获取负载最小的线程
 * @return
 */
MyThread *ThreadPool::getThread() const {
  return *std::min_element(_threads.begin(), _threads.end(),
                           [](MyThread *a, MyThread *b) -> bool {
                             return a->get_count() < b->get_count();
                           });
}

/**
 * @brief 减少目标线程负载数
 * @param target
 * @return
 */
bool ThreadPool::reduceThread(MyThread *target) {
  for (auto th : _threads) {
    if (th == target) {
      th->reduce();
      return true;
    }
  }
  return false;
}
